/**
 * @FileName: PromotionController.java
 * @Author
 * @Description:
 * @Date 2016年6月27日 下午2:31:12
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.BankCardBind;
import cn.hpclub.server.model.CmccCity;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.model.promotion.Promotion;
import cn.hpclub.server.service.BankCardBindService;
import cn.hpclub.server.util.ExcelRenderUtil;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ObjectUtil;
import cn.hpclub.server.util.excel.ExcelLogs;
import cn.hpclub.server.util.excel.ExcelUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @FileName: BankCardBindController.java
 * @Author zhl
 * @Description:
 * @Date 2016年12月14日 下午2:38:57
 * @CopyRight ZTE Corporation
 */
public class BankCardBindController extends BaseAdminController<BankCardBind>{
    private static final Logger logger                 = LoggerFactory.getLogger(MemberWhiteController.class);

    /**
     * 
     * @Title: list
     * @Description:分页获取绑定银行卡数据列表
     */
    public void list(){
        List<Record> list = InterfaceUtil.getAllCity();
        setAttr("city_list", list);// 加载地市列表

        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        int city_id = Integer.parseInt(getPara("city_id", "-1"));
        if(city_id==-1&&searchInfo.containsKey("city_id")){
            city_id = Integer.valueOf(searchInfo.get("city_id"));
        }

        // getAttr("so").hasPermission("VISIT_COUNT")

        if(city_id == -1){
            int org_id = InterfaceUtil.getOrgId();
            Record record = InterfaceUtil.getInfoByOrg(org_id);
            if(ObjectUtil.isNotEmpty(record) && ObjectUtil.isNotEmpty(record.getInt("city_id"))){
                city_id = record.getInt("city_id");
            }
        }
        if((!searchInfo.contains("city_id") || "-1".equals(searchInfo.get("city_id"))) && city_id != -1){
            searchInfo.put("city_id", String.valueOf(city_id));
        }
        int city_id_attr = city_id;
        if(StrKit.notBlank(searchInfo.get("city_id"))){
            city_id_attr = Integer.parseInt(searchInfo.get("city_id"));
        }
        setAttr("city_id", city_id_attr);

        if(StrKit.notBlank(searchInfo.get("city_id"))&&city_id!=-1){
            CmccCity cmccCity = CmccCity.dao.findById(city_id);
            searchInfo.put("group_id", cmccCity.getInt(CmccCity.GROUP_ID).toString());
            searchInfo.remove("city_id");
        }
        findByPageForSearch("SELECT b.*,oc.DisplayName as cmcc_name,oa.DisplayName as displayName ",
                new BankCardBindService().service.getSqlExceptSelect(searchInfo));
        render("/admin/bank_card_bind_list.tpl");
    }

    private Organization getCityByOrgId(int orgId){
        Organization organization = Organization.dao.findById(orgId);
        return organization;
    }


    /**
     * 导出到excel
     */
    public void exportAll(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        int city_id = Integer.parseInt(getPara("city_id", "-1"));
        if(city_id==-1&&searchInfo.containsKey("city_id")){
            city_id = Integer.valueOf(searchInfo.get("city_id"));
        }
        // getAttr("so").hasPermission("VISIT_COUNT")

        if(city_id == -1){
            int org_id = InterfaceUtil.getOrgId();
            Record record = InterfaceUtil.getInfoByOrg(org_id);
            if(ObjectUtil.isNotEmpty(record) && ObjectUtil.isNotEmpty(record.getInt("city_id"))){
                city_id = record.getInt("city_id");
            }
        }
        if((!searchInfo.contains("city_id") || "-1".equals(searchInfo.get("city_id"))) && city_id != -1){
            searchInfo.put("city_id", String.valueOf(city_id));
        }
        if("-1".equals(searchInfo.get("city_id"))){
            searchInfo.remove("city_id");
        }
        int city_id_attr = city_id;
        if(StrKit.notBlank(searchInfo.get("city_id"))){
            city_id_attr = Integer.parseInt(searchInfo.get("city_id"));
        }
        setAttr("city_id", city_id_attr);

        if(StrKit.notBlank(searchInfo.get("city_id"))&&city_id!=-1){
            CmccCity cmccCity = CmccCity.dao.findById(city_id);
            searchInfo.put("group_id", cmccCity.getInt(CmccCity.GROUP_ID).toString());
            searchInfo.remove("city_id");
        }

        SXSSFWorkbook workbook = new BankCardBindService().service.getExcel(searchInfo);
        render(new ExcelRenderUtil(workbook, "绑定银行卡"));
    }




    /**
     * 跳转到导入页面
     */
    public void importInit(){
        render("/admin/bank_card_bind_import.tpl");
    }


    public void uploadExcel(){
        String uploadFileName = "";
        File upload = null;
        UploadFile upfile = getFile();
        if(upfile != null){
            upload = upfile.getFile();
            uploadFileName = upfile.getFileName();
        }
        if(upload == null){
            ajaxJsonErrorMessage("请选择上传文件!");
            return;
        }
        String allowedUploadFileExtension = getSystemConfig().getAllowedUploadFileExtension().toLowerCase();
        if(StringUtils.isEmpty(allowedUploadFileExtension)){
            ajaxJsonErrorMessage("不允许上传文件!");
            return;
        }
        String fileExtension = StringUtils.substringAfterLast(uploadFileName, ".").toLowerCase();
        String[] fileExtensionArray = allowedUploadFileExtension.split(SystemConfig.EXTENSION_SEPARATOR);
        if(!ArrayUtils.contains(fileExtensionArray, fileExtension)){
            ajaxJsonErrorMessage("只允许上传文件类型: " + allowedUploadFileExtension + "!");
            return;
        }
        int uploadLimit = getSystemConfig().getUploadLimit() * 1024;
        if(uploadLimit != 0){
            if(upload != null && upload.length() > uploadLimit){
                ajaxJsonErrorMessage("文件大小超出限制!");
                return;
            }
        }
        long successCount = 0;
        long totalCount = 0;
        List<String> errorLogs = new ArrayList<>();
        try {
            InputStream in = new FileInputStream(upload);
            ExcelLogs logs = new ExcelLogs();
            Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, in, "yyyy/MM/dd HH:mm:ss", logs, 0);
            totalCount = importExcel.size();
            for(Map<?, ?> m : importExcel){
                BankCardBind bankCardBind = getBankCardBindData(m);
                if(StrKit.isBlank(bankCardBind.getStr(BankCardBind.LAST_MODIFY_TIME))){
                    bankCardBind.set(BankCardBind.LAST_MODIFY_TIME,null);
                }
                if(StrKit.isBlank(bankCardBind.getStr(BankCardBind.CREATE_TIME))){
                    bankCardBind.set(BankCardBind.CREATE_TIME,null);
                }
                try{
                    bankCardBind.save();
                    successCount++;
                }catch(Exception e){
                    logger.error(e.getMessage());
                    errorLogs.add(e.getMessage());
                }
            }
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            ajaxJsonErrorMessage("文件不存在， message:"+e.getMessage());
            return;
        } catch (InvalidFormatException e) {
            logger.error(e.getMessage());
            ajaxJsonErrorMessage("解析Excel文件出现异常， error message:"+e.getMessage());
            return;
        } catch (ActiveRecordException e){
            logger.error(e.getMessage());
            ajaxJsonErrorMessage("字段不匹配,  error message:"+e.getMessage());
            return;
        } catch(Exception e){
            logger.error(e.getMessage());
            ajaxJsonErrorMessage("系统异常,  error message:"+e.getMessage());
            return;
        }
        long failedCount = totalCount - successCount;
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put("message", "成功导入"+successCount+"条数据，失败"+failedCount+"条");
        jsonMap.put("errorLogs",errorLogs);
        renderJson(jsonMap);
    }



    private BankCardBind getBankCardBindData(Map<?, ?> map){
        BankCardBind bankCardBind = new BankCardBind();
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            String key = (String)entry.getKey();
            if(key.equals("地市") || key.equals("区县")) continue;
            String value = (String)entry.getValue();
            bankCardBind.set(getField(key),value);
        }
        return bankCardBind;
    }

    private String getField(String key){
        String fieldName = "";
        switch (key){
            case "开户名":
                fieldName = BankCardBind.ACCOUNT_NAME;
                break;
            case "银行卡号":
                fieldName = BankCardBind.CARD_NUMBER;
                break;
            case "开户行":
                fieldName = BankCardBind.REGIST_BANK;
                break;
            case "开户地":
                fieldName = BankCardBind.REGIST_AREA;
                break;
            case "支行信息":
                fieldName = BankCardBind.SUBBRANCH;
                break;
            case "工号":
                fieldName = BankCardBind.LOGIN_NO;
                break;
            case "银行代码":
                fieldName = BankCardBind.BANK_TYPE;
                break;
            case "手机号码":
                fieldName = BankCardBind.PHONE_NO;
                break;
            case "数据保存类型":
                fieldName = BankCardBind.BUSI_FLAG;
                break;
            case "创建时间":
                fieldName = BankCardBind.CREATE_TIME;
                break;
            case "最后修改时间":
                fieldName = BankCardBind.LAST_MODIFY_TIME;
                break;
            default:
                fieldName = "";
        }
        return fieldName;
    }


}
